package com.ruoyi.web.service.Impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.mysql.cj.protocol.Message;
import com.ruoyi.common.core.domain.MessageInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.web.mapper.MesConfigMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.web.mapper.MesCustomMapper;
import com.ruoyi.web.domain.mes.MesCustom;
import com.ruoyi.web.service.IMesCustomService;

import javax.annotation.Resource;

import static com.ruoyi.framework.socket.SocketIOServiceImpl.clientMap;

/**
 * 客户信息Service业务层处理
 *
 * @author levicash
 * @date 2024-01-04
 */
@Service
public class MesCustomServiceImpl implements IMesCustomService {
//    // 用来存已连接的客户端
//    private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();

    private static final Logger log = LoggerFactory.getLogger(IMesCustomService.class);
    @Resource
    private MesCustomMapper mesCustomMapper;

    @Resource
    private MesConfigMapper configMapper;

    /**
     * 查询客户信息
     *
     * @param id 客户信息主键
     * @return 客户信息
     */
    @Override
    public MesCustom selectMesCustomById(Long id) {
        return mesCustomMapper.selectMesCustomById(id);
    }

    /**
     * 查询客户信息列表
     *
     * @param mesCustom 客户信息
     * @return 客户信息
     */
    @Override
    public List<MesCustom> selectMesCustomList(MesCustom mesCustom) {
        return mesCustomMapper.selectMesCustomList(mesCustom);
    }

    /**
     * 新增客户信息
     *
     * @param mesCustom 客户信息
     * @return 结果
     */
    @Override
    public int insertMesCustom(MesCustom mesCustom) {
        mesCustom.setCreateBy(SecurityUtils.getUsername());
        mesCustom.setCreateTime(DateUtils.getNowDate());
        // 生成客户编号
        Map<String, Object> map = new HashMap<>();
        map.put("columnName", "code");
        map.put("tableName", "mes_custom");
        int maxNum = configMapper.getMaxId(map);
        String code = PinYinUtils.getCodeNormal(maxNum, "KHGL");
        mesCustom.setCode(code);
        return mesCustomMapper.insertMesCustom(mesCustom);
    }

    /**
     * 修改客户信息
     *
     * @param mesCustom 客户信息
     * @return 结果
     */
    @Override
    public int updateMesCustom(MesCustom mesCustom) {
        mesCustom.setUpdateBy(SecurityUtils.getUsername());
        mesCustom.setUpdateTime(DateUtils.getNowDate());
        return mesCustomMapper.updateMesCustom(mesCustom);
    }

    /**
     * 批量删除客户信息
     *
     * @param ids 需要删除的客户信息主键
     * @return 结果
     */
    @Override
    public int deleteMesCustomByIds(Long[] ids) {
        return mesCustomMapper.deleteMesCustomByIds(ids);
    }

    /**
     * 删除客户信息信息
     *
     * @param id 客户信息主键
     * @return 结果
     */
    @Override
    public int deleteMesCustomById(Long id) {
        return mesCustomMapper.deleteMesCustomById(id);
    }

    /**
     * 修改客户信息状态
     *
     * @param mesCustom 客户信息
     * @return 结果
     */
    @Override
    public int updateMesCustomStatus(MesCustom mesCustom) {
        mesCustom.setUpdateBy(SecurityUtils.getUsername());
        mesCustom.setUpdateTime(DateUtils.getNowDate());
        return mesCustomMapper.updateMesCustom(mesCustom);
    }


    /**
     * 通过客户信息名称查询客户信息
     *
     * @param name 客户信息名称
     * @return 客户信息
     */
    @Override
    public MesCustom selectMesCustomByName(String name) {
        return mesCustomMapper.selectMesCustomByName(name);
    }

    /**
     * 导入客户信息数据
     *
     * @param mesCustomList   客户信息数据
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importCustom(List<MesCustom> mesCustomList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(mesCustomList) || mesCustomList.size() == 0) {
            throw new ServiceException("导入客户信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (MesCustom custom : mesCustomList) {
            try {
                // 验证是否存在这个客户
                MesCustom m = mesCustomMapper.selectMesCustomByName(custom.getName());
                if (StringUtils.isNull(m)) {
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(custom.getPhone())) {
                        String tel = "^1[3|4|5|6|7|8|9][0-9]\\d{8}$"; // 手机号正则校验
                        if (!Pattern.matches(tel, custom.getPhone())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、联系电话 " + custom.getPhone() + " 有误");
                        }
                    }

                    custom.setCreateBy(operName);
                    mesCustomMapper.insertMesCustom(custom);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户信息 " + custom.getName() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、客户信息 " + custom.getName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户信息 " + custom.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
